package lvbu.wang.lvbuoperator.core;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;

import com.qing.library.utils.CoreUtil;
import com.qing.library.utils.L;
import com.qing.library.utils.SharedPreferenceUtil;
import com.qing.library.utils.ToastUtil;
import com.qing.library.widget.TipInfoLayout;

import lvbu.wang.lvbuoperator.LoginActivity;
import lvbu.wang.lvbuoperator.R;
import lvbu.wang.lvbuoperator.constants.ConstantsValue;
import lvbu.wang.lvbuoperator.services.BluetoothLEService;
import lvbu.wang.lvbuoperator.ui.index.IotIndexActivity;

/**
 * Created by DaiQing.Zha on 2016/9/14 0014.
 */
public abstract class BaseActivity extends CustomerAppcompatActivity {

    private Context mContext;
    public Context getContext() {
        return mContext;
    }
    protected boolean isTemplate=true; //是否使用模板
    protected Toolbar toolbar;
    public LinearLayout mainBody;            //主体 显示
    protected TipInfoLayout mTipInfoLayout;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CoreUtil.addAppActivity(this);
        // setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);  //禁止横屏
        mContext = this;
        if(savedInstanceState!=null){
            L.e("------------恢复------------->>");
        }
        if(isTemplate){
            setContentView(R.layout.core_template);
            initWidget();
        }else{

        }

        if(this instanceof LoginActivity || this instanceof IotIndexActivity){   //首页不需要返回键

        } else {
            if(getSupportActionBar()!=null){
                getSupportActionBar().setDisplayHomeAsUpEnabled(true);  //返回键
            }
        }
    }
    @Override
    public void setContentView(int layoutResID) {
        if(layoutResID == R.layout.core_template){
            super.setContentView(layoutResID);
        }else{
            if(mainBody!=null){
                mainBody.removeAllViews();
                mainBody.addView(this.getLayoutInflater().inflate(layoutResID,null),
                        new WindowManager.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT,
                                WindowManager.LayoutParams.MATCH_PARENT));
            }else{
                super.setContentView(layoutResID);
            }
            init();
        }
    }

    /**
     * 如果有SD卡，并且可用状态
     *
     * @return
     */
    public static boolean hasSDCardMounted() {
        String state = Environment.getExternalStorageState();
        if (state != null && state.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * 初始化
     */
    protected abstract void init();
    /**
     * 查找view
     */
    protected <T extends View> T findView(int id) {
        return (T) findViewById(id);
    }
    /**
     * 初化控件
     */
    protected void initWidget(){
        mainBody = (LinearLayout) findViewById(R.id.view_mainBody_id);
        toolbar= (Toolbar) findViewById(R.id.id_toolbar);
        toolbar.setTitleTextColor(getResources().getColor(android.R.color.white));
        setSupportActionBar(toolbar);
        mTipInfoLayout = (TipInfoLayout)findViewById(R.id.fl_panent_id);
    }

    protected Fragment mFragmentContent;

    /**
     * 设置正标题
     * @param titleName
     */
    public void setActionBarTitle(String titleName){
         getSupportActionBar().setTitle(titleName);
    }
    /**
     * 切换Fragment
     * @param resId 资源Id fragment 的布局文件id
     * @param to
     */
    protected void switchFragmentContent(int resId,Fragment to) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if(mFragmentContent != null){
            if (mFragmentContent != to) {
                if (!to.isAdded()) { // 先判断是否被add过
                    transaction.hide(mFragmentContent).add(resId, to); // 隐藏当前的fragment，add下一个到Activity中
                } else {
                    transaction.hide(mFragmentContent).show(to); // 隐藏当前的fragment，显示下一个
                }

            }
        }else{
            transaction.add(R.id.fl_panent_id, to);
        }
        transaction.commitAllowingStateLoss();  //推荐使用此方法，更安全，更方便
        mFragmentContent = to;
    }


    /**
     * 获取蓝牙连接状态
     * @param context
     * @return
     */
    public static int getMotorDefault_bluetooth_connect_state(Context context) {

        return (int) SharedPreferenceUtil.get(context, ConstantsValue.BLUETOOTH_CONNECT_STATE, BluetoothLEService.Bluetooth_UNCONNECT);
    }

    /**
     * 获取蓝牙连接状态
     * @return
     */
    public int getMotorDefault_bluetooth_connect_state() {
        return getMotorDefault_bluetooth_connect_state(mContext);
    }


    /**
     * 设置电机类型
     * @param context
     * @param motorType
     */
    public static void setMotorType(Context context, int motorType) {

        SharedPreferenceUtil.put(context, ConstantsValue.MOTOR_TYPE_KEY, motorType);
    }

    /**
     * 获取电机类型
     * @return
     */
    public int getMotorType() {
        return getMotorType(mContext);
    }

    /**
     * 获取电机类型
     * @param context
     * @return
     */
    public static int getMotorType(Context context) {

        return (int) SharedPreferenceUtil.get(context, ConstantsValue.MOTOR_TYPE_KEY, ConstantsValue.MOTOR_TYPE_IOT_OPERATION);
    }


    /**
     * 设置app版本类型
     * @param context
     * @param appVersion
     */
    public static void setAppVersion(Context context, int appVersion) {

        SharedPreferenceUtil.put(context, ConstantsValue.APP_VERSION_KEY, appVersion);
    }

    /**
     * 获取电机类型
     * @return
     */
    public int getAppVersion() {
        return getAppVersion(mContext);
    }

    /**
     * 获取电机类型
     * @param context
     * @return
     */
    public static int getAppVersion(Context context) {

        return (int) SharedPreferenceUtil.get(context, ConstantsValue.APP_VERSION_KEY, ConstantsValue.APP_VERSION);
    }

    /**
     * 设置蓝牙连接状态
     * @param context
     * @param bluetooth_connect_state
     */
    public static void saveMotorDefault_bluetooth_connect_state(Context context, int bluetooth_connect_state) {

        SharedPreferenceUtil.put(context, ConstantsValue.BLUETOOTH_CONNECT_STATE, bluetooth_connect_state);
    }

    /**
     * 设置蓝牙连接状态
     * @param bluetooth_connect_state
     */
    public void saveMotorDefault_bluetooth_connect_state(int bluetooth_connect_state) {
        saveMotorDefault_bluetooth_connect_state(mContext, bluetooth_connect_state);
    }
    public static void sleep(long time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取设备唯一标示
     * @param context
     * @return
     */
    public static String getCharacteristic(Context context) {
        return android.provider.Settings.System.getString(context.getContentResolver(), "android_id");
    }

    /**
     * 获取设备唯一标示
     * @return
     */
    public String getCharacteristic() {
        return getCharacteristic(mContext);
    }
    public static void setToken(Context context,String token){

        SharedPreferenceUtil.put(context, ConstantsValue.TOKEN,token);//保存token
    }

    public void setToken(String token){

        SharedPreferenceUtil.put(getContext(),ConstantsValue.TOKEN,token);//保存userPhone
    }

    /**
     * 获取token
     * @param context
     * @return
     */
    public static String getToken(Context context) {

        return (String) SharedPreferenceUtil.get(context,ConstantsValue.TOKEN,"");
    }

    /**
     * 获取token
     * @return
     */
    public String getToken() {
        return getToken(mContext);
    }

    public static String getNickname(Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(ConstantsValue.Shared_Preferences_Nickname, Context.MODE_PRIVATE);
        return sharedPreferences.getString("nickname", "");
    }

    public String getNickname() {
        return getNickname(mContext);
    }

    public void setNickname(String nickname) {
        SharedPreferences sharedPreferences = getSharedPreferences(ConstantsValue.Shared_Preferences_Nickname, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("nickname", nickname);
        editor.commit();
    }

    public String getPwd() {
        return getPwd(mContext);
    }
    public static String getPwd(Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(ConstantsValue.Shared_Preferences_Pwd, Context.MODE_PRIVATE);
        return sharedPreferences.getString("pwd", "");
    }
    public void setPwd(String nickname) {
        SharedPreferences sharedPreferences = getSharedPreferences(ConstantsValue.Shared_Preferences_Pwd, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("pwd", nickname);
        editor.commit();
    }

    public static int getManagerId(Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(ConstantsValue.Shared_Preferences_ManagerId, Context.MODE_PRIVATE);
        return sharedPreferences.getInt("managerId", 0);
    }

    public int getManagerId() {
        return getManagerId(mContext);
    }

    public void setManagerId(int managerId) {
        SharedPreferences sharedPreferences = getSharedPreferences(ConstantsValue.Shared_Preferences_ManagerId, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt("managerId", managerId);
        editor.commit();
    }

    /**
     * 设置蓝牙地址
     * @param context
     * @return
     */
    public static void setBluetoothAddress(Context context,String bluetoothAddress){

        SharedPreferenceUtil.put(context, ConstantsValue.SHARE_BLUETOOTH_ADDRESS, bluetoothAddress);
    }

    /**
     * 获取蓝牙地址
     * @param context
     * @return
     */
    public static String getBluetoothAddress(Context context) {

        try{
            return (String) SharedPreferenceUtil.get(context,ConstantsValue.SHARE_BLUETOOTH_ADDRESS,"");
        }catch (Exception e){
            return "";
        }
    }

    /**
     * 设置productId
     * @param context
     * @return
     */
    public static void setBluetoothProductId(Context context,String productId){

        SharedPreferenceUtil.put(context, ConstantsValue.LVBU_PRODUCT_ID, productId);
    }

    /**
     * 获取productId
     * @param context
     * @return
     */
    public static String getBluetoothProductId(Context context) {

        return (String) SharedPreferenceUtil.get(context,ConstantsValue.LVBU_PRODUCT_ID,"");
    }

    /**
     * 设置productName
     * @param context
     * @return
     */
    public static void setBluetoothProductName(Context context,String productId){

        SharedPreferenceUtil.put(context, ConstantsValue.LVBU_PRODUCT_NAME, productId);
    }

    /**
     * 获取productName
     * @param context
     * @return
     */
    public static String getBluetoothProductName(Context context) {

        return (String) SharedPreferenceUtil.get(context,ConstantsValue.LVBU_PRODUCT_NAME,"");
    }

    /**
     * 获取设备类型
     * @return
     */
    public static String getOrigin() {
        return "android";
    }

    private final int WHAT_SHOW_TOAST_ = 1000;
    /**
     * 更新UI线程的handler
     */
    private Handler mHandlerRefreshUI = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case WHAT_SHOW_TOAST_:
                    ToastUtil.showShortToast(BaseActivity.this,msg.obj.toString());
                    break;
            }
        }
    };
    /**
     * 显示toast信息
     * @param msg
     */
    public void showToastMsg(String msg){
        Message message = Message.obtain();
        message.what = WHAT_SHOW_TOAST_;
        message.obj = msg;
        mHandlerRefreshUI.sendMessage(message);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 获取版本名
     * @return
     */
    public String getVersionName() {
        return getVersionName(mContext);
    }

    /**
     * 获取版本名
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            // CrashReport.postCatchedException(e);
        }
        return verName;
    }

}
